
var nav = document.querySelector('#nav');
var iframe_parent = document.querySelector('.iframe-parent');

var windowWidth = document.body.clientWidth;
window.onresize = function () {
	windowWidth = document.body.clientWidth;
}
/**
* 后面添加跳转
* 获取跳转节点的父节点 比如: var nav = document.querySelector('#nav');
* 然后添加事件监听 比如: nav.addEventListener('click', navgoToUrl);
* 注意，需要在页面上的跳转节点上添加 data-url="路径" 比如: <a data-url='./find-lawyer.html' href="#">找律师</a>
*/

// 事件监听跳转
addEventListener(nav,'click', navgoToUrl);
addEventListener(document.querySelector('#iframe'),'load', setIframeHeight);

// 事件监听iframe高度
var num = 0;
function setIframeHeight() {
	var iframe = document.querySelector('#iframe');
	if (iframe) {
		var iframeWin = iframe.contentWindow.document || iframe.contentDocument;
		var body = iframeWin.frames && iframeWin.frames.document ? iframeWin.frames.document.body || iframeWin.frames.document.activeElement : null;
		var html = iframeWin.body || iframeWin.activeElement || iframeWin.documentElement || iframeWin.doctype || body || null;
		if (html) {
			++num;
			iframe.height = (html.scrollHeight || html.clientHeight);
			// document.querySelector('.l-log').innerText = num;
		}
	}
};

function removeElement(_element){
	 var _parentElement = _element.parentNode;
	 if(_parentElement){
			_parentElement.removeChild(_element);
	 }
}

function addEventListener(_element,event,fun){
	_element.addEventListener(event,fun);
}

// 事件委托,函数防抖,间隔500毫秒才能点击
var delay = null;
function navgoToUrl(e){
	if(delay){
		return
	}
	delay = setTimeout(function() {
		console.log('计时器...')
		try{
			var el = e.target || e.srcElement || e.toElement || null;
			if(el){
				var url = el.dataset && el.dataset.url || '';
				var iframe = document.querySelector('#iframe');
				if(windowWidth > 999){
					url && (iframe.src = url);
				}else{
					if(url){
						removeElement(iframe);
						var iframeNode = document.createElement('iframe');
						iframe_parent.appendChild(iframeNode);
						addEventListener(iframeNode,'load', setIframeHeight);
						iframeNode.frameBorder = '0';
						iframeNode.classList = "embed-responsive-item";
						iframeNode.id = "iframe";
						iframeNode.style.width = '100%';
						iframeNode.scrolling = 'no';
						iframeNode.src = url;
					}
				}
				delay = null;
			}
		}catch(e){
			delay = null;
		}
	},500)
}
